<?php
/**
 * Created by PhpStorm.
 * Script Name: Bottj.php
 * Create: 2023/3/18 8:30
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use plugin\wechat\app\model\BotGroupmember as GroupMemberM;
use plugin\wechat\app\model\BotMember as MemberM;
use plugin\wechat\app\model\Bot as BotM;
use plugin\wechat\app\model\BotTjgroup as TjGroupM;
use plugin\wechat\app\service\Bot as BotService;
use app\common\service\Tenant as TenantService;
use support\Request;

class Bottj extends BotBase
{
    /**
     * @var BotM
     */
    private BotM $botM;

    public function __construct()
    {
        parent::__construct();
        $this->botM = new BotM();
    }

    /**
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request){
        $group_member_m = new GroupMemberM();
        $member_m = new MemberM();
        $bot_list = BotM::where('status', 1)
            ->where([TenantService::tenantIdWhere()])
            ->field(['id,title,uin'])
            ->select();
        if($request->isPost()){
            $end = strtotime(date('Ymd 00:00:00'));
            $begin = $end - 29 * 86400;
            $x_data = [];
            for($i = $begin; $i <= $end; $i+=86400){
                $x_data[] = date('m-d', $i);
            }
            //好友数据
            $legends = [];
            $series = [];
            $member_where = [['type','=', BotService::FRIEND]];
            foreach ($bot_list as $bot){
                $legends[] = $bot['title'];
                $temp = [
                    'name' => $bot['title'],
                    'data' => []
                ];
                $member_where[] = ['uin', '=', $bot['uin']];
                for($i = $begin; $i <= $end; $i+=86400){
                    $member_where[] = ['create_time', 'between', [$i, $i + 86399]];
                    $temp['data'][] = $member_m->where($member_where)->count();
                }
                $series[] = $temp;
            }
            //群员数据
            $return = [
                'member_data' => ['xData' => $x_data, 'legends' => $legends, 'series' => $series]
            ];
            return $this->success('', '', $return);
        }

        $bots = BotM::where([
            TenantService::tenantIdWhere(),
            ['status', '=', 1]
        ])->column('uin', 'id');
        $bot_ids = array_keys($bots);
        $bot_wxids = array_values($bots);
        $where_member = [
            ['uin', 'in', $bot_wxids ? $bot_wxids : [0]],
            ['type', '=',  BotService::FRIEND]
        ];
        $where_group = [
            ['uin', 'in', $bot_wxids ? $bot_wxids : [0]],
            ['type', '=',  BotService::GROUP]
        ];

        $where_today = [
            ['create_time' ,'>', strtotime(date('Ymd 00:00:00'))]
        ];
        $today_tj = TjGroupM::where([['day', '=', date('Y-m-d')], BotService::tenantBotWhere()])
            ->find();

        $assign = [
            'bot_num' => count($bot_ids),
            'member_num' => [
                'total' => $member_m->where($where_member)->count(),
                'today' => $member_m->where($where_member + $where_today)->count()
            ],
            'group_num' => [
                'total' => $member_m->where($where_group)->count(),
                'today' => $member_m->where($where_group + $where_today)->count()
            ],
            'group_member' => [
                'total' => $group_member_m->where('bot_id' ,'in', $bot_ids ? $bot_ids : [0])->count(),
                'today_add' => empty($today_tj) ? 0:$today_tj['add_num'],
                'today_decr' => empty($today_tj) ? 0:$today_tj['decr_num']
            ],
            'bot_list' => $bot_list
        ];
        return $this->show($assign);
    }

    public function getGroupData(){
        if(request()->isPost()){
            $bot_ids = input('post.botid');
            if(empty($bot_ids) && $this->botM->where([TenantService::tenantIdWhere(), ['status', '=', 1]])->count()){
                return $this->error('至少选择一个机器人');
            }
            $end = strtotime(date('Ymd 00:00:00'));
            $begin = $end - 29 * 86400;
            $x_data = [];

            //好友数据
            $legends = ["进群人数", "退群人数", "净增人数"];

            $add_data = ['name' => '进群人数', 'data' => []];
            $decr_data = ['name' => '退群人数', 'data' => []];
            $netinc_data = ['name' => '净增人数', 'data' => []];
            $where = [
                TenantService::tenantIdWhere(),
                ['bot_id', 'in', $bot_ids]
            ];
            $tj_m = new TjGroupM();
            for($i = $begin; $i <= $end; $i+=86400){
                $x_data[] = date('m-d', $i);
                $where[] = ['day', '=', date('Y-m-d', $i)];
                $add_data['data'][] = $tj_m->where($where)->sum('add_num');
                $decr_data['data'][] = $tj_m->where($where)->sum('decr_num');
                $index = count($add_data['data']) - 1;
                $netinc_data['data'][] = $add_data['data'][$index] - $decr_data['data'][$index];
            }
            $series = [$add_data, $decr_data, $netinc_data];

            $return = ['xData' => $x_data, 'legends' => $legends, 'series' => $series];
            return $this->success('', '', $return);
        }
    }
}